# coding: utf-8
# @Author: ChuiZi
import pytest
import os
import threading

from shutil import copyfile

from settings import *
from options.configs import FrameDataPath
from lib.common import baseFunc, achievePath
from lib.frameTool import createTestCase, reportPatch, createPort


def run(report_format: int = 0):
    """
    0:为html类型测试报告,1:为allure类型测试报告
    :return: 默认生成位置在根目录下report文件夹内
    """
    report_type = {
        0: __htmlReport,
        1: __allureReport,
    }
    # 框架内部文件管理:创建及删除
    __manageFolder()
    # 接口mock模块在其他线程
    if mockPort["switch"]:
        web_mock_port = threading.Thread(name="web mock port", target=createPort.run)
        web_mock_port.daemon = True
        web_mock_port.start()
    # 生成测试用例
    createTestCase.CreateTestCase().run(report_format)
    # 执行测试
    baseFunc.callSelf(report_type[report_format])


# <editor-fold desc="测试报告类型">
# 生成html格式的测试报告
def __htmlReport():
    report_type = "2"
    pytest.main([
        '--report=_测试报告.html',
        f'--title={info.get("projectName")}测试报告',
        f'--tester={info.get("tester")}',
        f'--desc={info.get("reportDescript")}',
        f'--template={report_type}'])
    # 测试报告格式修改,编码转换
    if report_type == "2":
        reportPatch.htmlReportPatch()


# 生产allure格式的测试报告
def __allureReport():
    import os
    pytest.main(['-s', '-v', '{0}'.format(FrameDataPath.pathTestCaseDir), '--clean-alluredir',
                 '--alluredir={0}'.format(FrameDataPath.pathReportDirAllureTemp)])
    copyfile(FrameDataPath.pathReportAllureConfig, fr"{FrameDataPath.pathReportDirAllureTemp}\environment.properties")
    os.system(r'allure generate {0} -c -o {1}'.format(FrameDataPath.pathReportDirAllureTemp,
                                                      FrameDataPath.pathReportDir))
    copyfile(FrameDataPath.pathReportAllureUse, fr"{FrameDataPath.pathReportDir}\双击打开测试报告.bat")


# </editor-fold>
# <editor-fold desc="文件夹管理">

# 测试报告文件夹的清理和创建
def __manageFolder():
    """测试报告文件夹的清理和创建"""
    try:
        os.mkdir(FrameDataPath.pathReportRootDir)
        os.mkdir(FrameDataPath.pathReportDir)
        os.mkdir(FrameDataPath.pathReportDirAllureTemp)
    except FileExistsError:
        pass
    # 删除所有测试报告
    for file in achievePath.Find.suffixeAbsPaths(FrameDataPath.pathReportRootDir, "html"):
        os.remove(file)


# </editor-fold>

if __name__ == '__main__':
    run(0)
